package com.person.mall.service.Impl;

import com.person.mall.dao.OrderItemMapper;
import com.person.mall.dao.OrderMapper;
import com.person.mall.dao.ProductMapper;
import com.person.mall.dao.ShippingMapper;
import com.person.mall.enums.OrderStatusEnum;
import com.person.mall.enums.ProductDetailEnum;
import com.person.mall.enums.ResponseEnum;
import com.person.mall.pojo.*;
import com.person.mall.service.ICartService;
import com.person.mall.service.IOrderService;
import com.person.mall.vo.OrderVo;
import com.person.mall.vo.ResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import sun.text.CollatorUtilities;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static com.person.mall.enums.ResponseEnum.*;

/**
 * @author 最酷的桃儿wjc
 * * @date 2022/5/26
 */
public class OrderServiceImpl implements IOrderService {

    @Autowired
    private ShippingMapper shippingMapper;

    @Autowired
    private ICartService iCartService;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Override
    @Transactional
    public ResponseVo<OrderVo> createOrder(Integer uid, Integer shippingId) {
        //收货地址校验
        Shipping shipping = shippingMapper.selectAllByIdAndShippingId(uid, shippingId);
        if (shipping == null){
            return ResponseVo.error(SHIPPING_NOT_EXITS);
        }
        //将购物车当中选中的商品放到集合当中
        List<Cart> cartList  = iCartService.cartListForSelect(uid).stream()
                .filter(Cart::getProductSelected)
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(cartList)){
            return ResponseVo.error(CART_SELECT_IS_EMPTY);
        }

//        再将购物车当中的id放到set集合中，进行SQL一次性查询
        Set<Integer> productSet = cartList.stream()
                .map(Cart::getProductId)
                .collect(Collectors.toSet());

//        查出商品集合
        List<Product> productList = productMapper.selectByProductIdSet(productSet);
//        根据商品id建成map集合用来校验商品
        Map<Integer, Product> productMap = productList.stream()
                .collect(Collectors.toMap(Product::getId, product -> product));


        List<OrderItem> orderItemList= new ArrayList<>();
//        生成orderNo
        Long orderNo = generateCreateNo();
        for (Cart cart : cartList) {
            Product product = productMap.get(cart.getProductId());
//            检查该商品是否存在
            if (product == null){
                return ResponseVo.error(PRODUCT_OFF_ERROR,"商品不存在" + cart.getProductId());
            }
//            商品是否下架或删除
            if (ProductDetailEnum.ON_SALE.getCode().equals(product.getStatus())){
                return ResponseVo.error(PRODUCT_OFF_ERROR);
            }
//            检查库存是否充足
            if (product.getStock() < cart.getQuantity()){
                return ResponseVo.error(PRODUCT_STOCK_ERROR,"库存不正确:"+product.getName());
            }


//            设置订单明细
            OrderItem orderItem = buildOrderitem(uid, orderNo, product, cart.getQuantity());
            orderItemList.add(orderItem);
            //减库存
            product.setStock(product.getStock()-cart.getQuantity());
            int count = productMapper.updateByPrimaryKeySelective(product);
            if (count <= 0){
                return ResponseVo.error(ORDER_ERROR);
            }

        }

        //            生成order对象
        Order order = buildOrder(uid, orderNo, shippingId, orderItemList);
//        写入订单表
        int row = orderMapper.insertSelective(order);
        if (row <= 0){
            return ResponseVo.error(ORDER_ERROR);
        }
//        写入订单明细表
        int rowOrderItem = orderItemMapper.batchInsert(orderItemList);
        if(rowOrderItem <= 0){
            return ResponseVo.error(ORDER_ERROR);
        }

        //更新购物车

        //构造Vo对象

        return ResponseVo.success(SUCCESS);
    }

    private Order buildOrder(Integer uid,Long orderNo,Integer shippingId,List<OrderItem> orderItemList) {
        Order order = new Order();
//        对价格进行计算
        BigDecimal paymentPrice = orderItemList.stream()
                .map(OrderItem::getTotalPrice)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        order.setOrderNo(orderNo);
        order.setUserId(uid);
        order.setShippingId(shippingId);
        order.setPayment(paymentPrice);
        order.setPaymentType(1);
        order.setPostage(0);
        order.setStatus(OrderStatusEnum.NO_PAY.getCode());
        return order;
    }

    private Long generateCreateNo() {
        return System.currentTimeMillis() + new Random().nextInt(999);
    }

    private OrderItem buildOrderitem(Integer uid,Long orderNo,Product product,Integer quantity) {
        OrderItem orderItem = new OrderItem();
        orderItem.setUserId(uid);
        orderItem.setOrderNo(orderNo);
        orderItem.setProductId(product.getId());
        orderItem.setProductName(product.getName());
        orderItem.setProductImage(product.getMainImage());
        orderItem.setCurrentUnitPrice(product.getPrice());
        orderItem.setQuantity(quantity);

        orderItem.setTotalPrice(product.getPrice().multiply(BigDecimal.valueOf(quantity)));
        return orderItem;
    }
}
